/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.testimonials;

import com.blandware.atleap.common.TestimonialModuleConstants;
import com.blandware.atleap.model.testimonials.Testimonial;
import com.blandware.atleap.service.testimonials.TestimonialManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.testimonials.TestimonialForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.testimonials.TestimonialModuleWebConstants;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * <p>Prepares form bean to update testimonial body</p>
 * <p/>
 * <p><a href="CallUpdateTestimonialBodyAction.java.html"></a><i>View source</i></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.11 $ $Date: 2008/04/29 17:52:51 $
 * @struts.action path="/testimonials/callUpdateTestimonialBody"
 * input="inputForward"
 * name="testimonialForm"
 * scope="request"
 * validate="false"
 * roles="testimonials-item-update"
 * @struts.action-forward name="inputForward"
 * path=".testimonials.updateTestimonial"
 * @struts.action-forward name="updateTestimonialBody"
 * path=".testimonials.updateTestimonialBody"
 * @struts.action-forward name="listTestimonials"
 * path="/testimonials/list.do"
 * redirect="true"
 */
public final class CallUpdateTestimonialBodyAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		request.getSession().removeAttribute(TestimonialModuleWebConstants.TESTIMONIAL_SUBMITTED_ACTION_KEY);

		if ( isCancelled(request) ) {
            request.getSession().removeAttribute(TestimonialModuleWebConstants.TESTIMONIAL_MERGED_BODY_KEY);
            if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
				String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(redirectUrl, true);
			}
			return mapping.findForward("listTestimonials");
		}
		TestimonialForm testimonialForm = (TestimonialForm) form;

		// Check whether user came here not from previous page (or he switched
		// edit mode/language during editing testimonial)
		String localesMode = testimonialForm.getLocalesMode();
		if ( !"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode) && testimonialForm.getBodyCheckedBoxes().size() == 0 ) {
			request.setAttribute("beginPage", mapping.findForward("listTestimonials").getPath());
			return mapping.findForward("unsatisfiablePage");
		}

		if ( !WebappUtil.hasCorrectValues(testimonialForm.getTitleMap()) ) {
			// title must be specified

            // check 'check all' ckeckbox if needed
            testimonialForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

			request.getSession().removeAttribute(TestimonialModuleWebConstants.TESTIMONIAL_SUBMITTED_ACTION_KEY);
			ActionMessages errors = new ActionMessages();
			errors.add("title", new ActionMessage("core.commons.errors.required", getMessage(request, "testimonials.form.title")));
			saveErrors(request, errors, false);
			saveToken(request);
			return mapping.getInputForward();
		}

		Long testimonialId;
		if ( testimonialForm.getId() != null ) {
			testimonialId = Long.valueOf(testimonialForm.getId());
		} else if ( request.getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_ID_KEY) != null ) {
			testimonialId = (Long) request.getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_ID_KEY);
		} else if ( request.getSession().getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_ID_KEY) != null ) {
			testimonialId = (Long) request.getSession().getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing testimonial item ID. Returning to list...");
			}
			return mapping.findForward("listTestimonials");
		}

		if ( !"current".equals(localesMode) && !"all".equals(localesMode) ) {
			localesMode = "selected";
		}
		testimonialForm.setLocalesMode(localesMode);

		TestimonialManager testimonialManager = (TestimonialManager) getBean(TestimonialModuleConstants.TESTIMONIAL_MANAGER_BEAN);
		Testimonial testimonial = testimonialManager.retrieveTestimonial(testimonialId);
		if ( testimonial == null ) {
			// testimonial not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("testimonialNotFound", new ActionMessage("testimonials.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listTestimonials");
		}

		if ( request.getSession().getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_MERGED_BODY_KEY) != null ) {
			Map mergedBody = (Map) request.getSession().getAttribute(TestimonialModuleWebConstants.TESTIMONIAL_MERGED_BODY_KEY);
			testimonialForm.setBodyMap(mergedBody);
			request.getSession().removeAttribute(TestimonialModuleWebConstants.TESTIMONIAL_MERGED_BODY_KEY);
		}

		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();

		request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("updateTestimonialBody");
	}
}
